<template>
  <div class="update-avatar">
    <img :src="src" ref="image"/>

    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="submitImg">完成</span>
    </div>
  </div>
</template>

<script>
// 1. 安装并导入 cropper
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import {setUserPhoto} from '@/api/user'

export default {
  props: ['src'],
  data() {
    return {
      cropper: ''
    }
  },
  mounted() {
    this.corpperInit()
  },
  methods: {
    corpperInit() {
      // 2. 获取 图片 元素
      const image = this.$refs.image

      // 3. 按照 cropper 文档 创建裁切对象
      this.cropper = new Cropper(image, {
        viewMode: 1, // 只能在裁剪的图片范围内移动
        dragMode: 'move', // 画布和图片都可以移动
        aspectRatio: 1, // 裁剪区默认正方形
        autoCropArea: 1, // 自动调整裁剪图片
        cropBoxMovable: false, // 禁止裁剪区移动
        cropBoxResizable: false, // 禁止裁剪区缩放
        background: false // 关闭默认背景
      })
    },
    submitImg() {
      this.cropper.getCroppedCanvas().toBlob(async blob => {
        const formData = new FormData()

        formData.append('photo', blob)

        // 发请求 提交 formData数据
        const {data: {data: {photo}}} = await setUserPhoto(formData)

        console.log(photo)
        this.$emit('close')
        this.$emit('update-photo', photo)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.update-avatar {
  background: #000;
  width: 100%;
  height: 100%;
  img {
    width: 100%;
  }
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
